<?php


namespace common\service;

use common\model\EpisodeStepCategorySealTimeModel;
use common\model\ProjectModel;
use common\model\StepCategoryModel;
use support\ErrorCode;
use support\SingletonTrait;


class EpisodeStepCategorySealTimeService
{
    use SingletonTrait;

    /**
     * 单环节封板时间列表
     * @param $filter
     * @param $page
     * @param $tenantId
     * @return array
     * @throws \think\Exception
     */
    public function EpisodeStepCategoryList($filter, $page, $tenantId)
    {
        $episodeStepCategoryList = model(EpisodeStepCategorySealTimeModel::class)
            ->where($filter)
            ->where(['tenant_id' => $tenantId])
            ->field('id,entity_id,project_id,step_category_ids,step_category_code,seal_time')
            ->select();

        $project = model(ProjectModel::class)->find($filter['project_id']);
        if (empty($project)) {
            throw_strack_exception('project not found', ErrorCode::PROJECT_NOT_FOUND);
        }
        $defaultStepCategoryList = TemplateService::getInstance()->findStepCategoryShowList();

        if (empty($defaultStepCategoryList)) {
            return [
                'total' => 0,
                'rows' => []
            ];
        }

        $selectEpisodeWithAllocationParam = [
            'param' => [
                'filter' => ['project_id' => $filter['project_id']],
                'fields' => 'episode_allocation.id,entity.id,entity.name,entity.code',
                'page' => $page
            ]
        ];
        $EpisodeAllocationList = EpisodeAllocationService::getInstance()->selectEpisodeWithAllocation($selectEpisodeWithAllocationParam);
        if (empty($EpisodeAllocationList['rows'])) {
            return [
                'total' => 0,
                'rows' => []
            ];
        }

        // 查询环节
        $episodeStepCategoryMap = [];
        if (!empty($episodeStepCategoryList)) {
            $stepCategoryCods = array_column($episodeStepCategoryList, 'step_category_code');
            $stepCategoryList = model(StepCategoryModel::class)->where(['code' => ['IN', $stepCategoryCods]])->field('id,code,name')->select();
            if (empty($stepCategoryList)) {
                return [];
            }
            $stepCategoryMap = array_column($stepCategoryList, null, 'code');

            $episodeStepCategoryList = array_map(function ($tmp) use ($stepCategoryMap) {
                $tmp['step_category_name'] = $stepCategoryMap[$tmp['step_category_code']]['name'] ?? '';
                return $tmp;
            }, $episodeStepCategoryList);

            $episodeStepCategoryMap = array_group_by($episodeStepCategoryList, 'entity_id');
        }
        $episodeStepCategoryReturnList = $EpisodeAllocationList['rows'];


        // 返回参数处理
        $episodeStepCategoryReturnList = array_map(function ($tmp) use ($episodeStepCategoryMap) {

            $tmp['episode_step_category_seal_time_info'] = $episodeStepCategoryMap[$tmp['id']] ?? [];
            return $tmp;
        }, $episodeStepCategoryReturnList);

        return [
            'total' => $EpisodeAllocationList['total'],
            'rows' => [
                'step_category_column' => $defaultStepCategoryList,
                'episode_step_category_list' => $episodeStepCategoryReturnList
            ]
        ];
    }

    /**
     * 设置单环节封板时间
     * @param $data
     * @param $tenantId
     * @return array
     * @throws \Exception
     */
    public function SetEpisodeStepCategory($data, $tenantId)
    {
        // 存在编辑,不存在新增
        $episodeStepCategorySealTimeData = model(EpisodeStepCategorySealTimeModel::class)
            ->where([
                'entity_id' => $data['entity_id'],
                'project_id' => $data['project_id'],
                'step_category_ids' => $data['step_category_ids'],
                'step_category_code' => $data['step_category_code'],
                'tenant_id' => $tenantId
            ])
            ->find();
        if (!empty($episodeStepCategorySealTimeData)) {
            $data['id'] = $episodeStepCategorySealTimeData['id'];
            return model(EpisodeStepCategorySealTimeModel::class)->modifyItem($data);
        }
        $data['tenant_id'] = $tenantId;
        return model(EpisodeStepCategorySealTimeModel::class)->addItem($data);
    }
}